/*


 */

package bankserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;

/**
 *
 *
 */
public class ClientDriver {
    
    private Bank bank;
    
    public ClientDriver(Bank bank) {
        this.bank = bank;
    }
    
    public void run() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        
        Account account = null;
        
        while (true) {
            String command = reader.readLine();
            
            String[] splits = command.split(" ");
            
            if (command.equals("exit")) {
                break;
            }
            else if (splits[0].equals("login") && splits.length>=2) {
                String name = splits[1];
                account = bank.getAccount(name);
            }
            else if (splits[0].equals("balance") && account != null) {
                System.out.println("Balance is " + account.getBalance());
            }
            else if (splits[0].equals("deposit") && splits.length>=2 && account != null) {
                Double amount = Double.valueOf(splits[1]);
                account.deposit(amount);
            }
            else if (splits[0].equals("withdraw") && splits.length>=2 && account != null) {
                Double amount = Double.valueOf(splits[1]);
                account.withdraw(amount);
            }
        }
                
    }
    
	public static void main(String[] args) throws Exception {
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new RMISecurityManager());
		}
                
                // The client must specify where to find the bank server
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                String host = "localhost";
                String port = "1099";
                System.out.println("Specify the bankserver ip:");
        
                while (true) {
                    String command = reader.readLine();
            
                    if (!command.equals("")) {
                        host = command +":"+ port;
                        break;
                    }
                    Thread.sleep(10);
                }

		System.out.println("Host: " + host);
		
		// Use the EHR service
		Bank bank = (Bank) Naming.lookup("//" + host + "/BankOfDoom");  
                System.out.println("Connected to: //" + host + "/BankOfDoom");
                ClientDriver driver = new ClientDriver(bank);
                driver.run();
	}

}
